﻿using Dapper;
using ERPEF.Model;
using ERPIService;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    //仓库盘点控制器
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InvWarehouseInventoryController : ControllerBase
    {
        private readonly inv_WarehouseService inv_WarehouseService;
        private readonly MyDbContext myDbContext;
        public InvWarehouseInventoryController(MyDbContext myDb, inv_WarehouseService inv_WarehouseService)
        {
            myDbContext = myDb;
            this.inv_WarehouseService = inv_WarehouseService;
        }


        /// <summary>
        /// 仓库盘点主表分页查询
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        public ActionResult<FenYe<inv_WarehouseInven>> GetFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "iwi_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "inv_WarehouseInven"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<inv_WarehouseInven>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<inv_WarehouseInven> fenYe = new FenYe<inv_WarehouseInven>()
                {
                    IwiData = result,
                    Rows = row,
                };
                if (fenYe.IwiData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }



        /// <summary>
        /// 仓库盘点从表分页查询
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        public ActionResult<FenYe<inv_WarehouseInven_C>> GetFenYeC(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "iwi_C_ID"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "inv_WarehouseInven_C"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<inv_WarehouseInven_C>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<inv_WarehouseInven_C> fenYe = new FenYe<inv_WarehouseInven_C>()
                {
                    IwiDataC = result,
                    Rows = row,
                };
                if (fenYe.IwiDataC.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }






        /// <summary>
        /// 添加盘点信息
        /// </summary>
        /// <param name="AddReturn"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddReturn([FromBody] inv_WarehouseInven inv_WarehouseInven)
        {
            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxCodeNumber());

            // 生成新编码
            string newCode = GenerateSaleCode(maxCodeNumber);

            inv_WarehouseInven.iwi_code = newCode;

            if (ModelState.IsValid)
            {

                int result = await inv_WarehouseService.Add(inv_WarehouseInven);
                if (result > 0)
                {
                    await myDbContext.SaveChangesAsync();

                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        private async Task<string> GetMaxCodeNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxCodeString = await myDbContext.inv_WarehouseInven
                .Where(w => w.iwi_code.StartsWith("CKPD"))
                .Select(w => w.iwi_code.Substring(12))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxCodeString))
            {
                return "01";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxCodeString);
            Console.WriteLine(maxCodeNumber);

            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了99，则重置为01
            if (newCodeNumber > 99)
            {
                newCodeNumber = 1;
            }
            return newCodeNumber.ToString();

        }
        // 生成新的仓库编码
        private string GenerateSaleCode(int codeNumber)
        {
            // 获取当前日期的字符串表示形式，格式为 "yyyyMMdd"
            string dateString = DateTime.Now.ToString("yyyyMMdd");

            // 将数字转换为两位字符串，并在前面补零
            string codeString = codeNumber.ToString("D2");

            // 返回完整的编码，包括前缀 "XSDD"、日期部分和数字部分
            return "CKPD" + dateString + codeString;
        }


        /// <summary>
        /// 根据仓库查询物品库存
        /// </summary>
        /// <param name="AddReturn"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryProducts(string igi_warehouse)
        {
            if (string.IsNullOrEmpty(igi_warehouse))
            {
                return BadRequest("仓库名称不能为空");
            }

            var inventoryItems = await inv_WarehouseService.GetInventoryByWarehouseAsync(igi_warehouse);

            if (inventoryItems == null || !inventoryItems.Any())
            {
                return NotFound("未找到该仓库的物品库存");
            }

            return Ok(inventoryItems);
        }


        /// <summary>
        /// 修改主表
        /// </summary>
        /// <returns></returns> 
        [HttpPut]
        public async Task<IActionResult> UpdateInv(inv_WarehouseInven inv_WarehouseInven)
        {
            if (ModelState.IsValid)
            {
                inv_WarehouseInven.inv_WarehouseInven_C = null;
                int result = await inv_WarehouseService.Update(inv_WarehouseInven);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }


        /// <summary>
        /// 从表修改
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update_C(inv_WarehouseInven_C data)
        {
            if (ModelState.IsValid)
            {
                int result = await inv_WarehouseService.Update_C(data);
                if (result > 0)
                {
                    return Ok("修改成功");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        /// <summary>
        /// 从表添加
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add_C(inv_WarehouseInven_C data)
        {
            if (ModelState.IsValid)
            {
                int result = await inv_WarehouseService.Add_C(data);
                if (result > 0)
                {
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }


        /// <summary>
        /// 仓库盘点审核
        /// </summary>
        /// <param name="iwi_id"></param>
        /// <returns></returns>
        [HttpPost("{iwi_id}")]
        public async Task<IActionResult> AuditWarehouseInven(int iwi_id)
        {
            // 从数据库中获取销售订单及其关联的订单详情
            var WarehouseInven = await myDbContext.inv_WarehouseInven
                .Include(so => so.inv_WarehouseInven_C) // 确保加载关联的订单详情
                .FirstOrDefaultAsync(so => so.iwi_id == iwi_id);

            // 如果入库单不存在或已经被逻辑删除，则返回错误信息
            if (WarehouseInven == null || WarehouseInven.IsDeleted)
            {
                return NotFound("未找到对应的数据");
            }
            if (WarehouseInven.iwi_AuditStatus == true)
            {
                return BadRequest("该订单已进行了盘点，不能再进行审核");
            }
            try
            {
                // 审核销售订单
                WarehouseInven.iwi_AuditStatus = true;
                WarehouseInven.iwi_auditor = "Admin";
                WarehouseInven.iwi_auditTime = DateTime.UtcNow;

                if (WarehouseInven.iwi_AuditStatus == true)
                {

                    foreach (var returnItem in WarehouseInven.inv_WarehouseInven_C)
                    {
                        if (returnItem.BreakState == 1)
                        {
                            var inv_storage = new inv_Storage
                            {
                                ow_id = 0,
                                ow_item_name = returnItem.igi_name,
                                ow_specification = WarehouseInven.iwi_code,
                                ow_item_attributes = "产品",
                                ow_unit = "包",
                                ow_quantity = returnItem.breakQuantity,
                                ow_warehouse = returnItem.igi_warehouse,
                                ow_operators = WarehouseInven.iwi_checker,
                                ow_storage_date = DateTime.Now,
                                ow_type = "盘盈入库",
                                ow_audit = false,
                                IsDeleted = false,
                                ow_create_by = "Admin",
                                ow_create_time = DateTime.Now,
                                ow_update_by = "Admin",
                                ow_update_time = DateTime.Now,
                            };
                            myDbContext.inv_Storage.Add(inv_storage);
                        }
                        else if (returnItem.BreakState == 2)
                        {
                            var inv_other_outbound = new inv_other_outbound
                            {
                                ioo_id = 0,
                                ioo_item_name = returnItem.igi_name,
                                ioo_specification = WarehouseInven.iwi_code,
                                ioo_item_attributes = "产品",
                                ioo_unit = "包",
                                ioo_quantity = (int)returnItem.breakQuantity,
                                ioo_warehouse = returnItem.igi_warehouse,
                                ioo_operators = WarehouseInven.iwi_checker,
                                ioo_outbound_date = DateTime.Now,
                                ioo_type = "盘亏出库",
                                ioo_audit = false,
                                IsDeleted = false,
                                ioo_create_by = "Admin",
                                ioo_create_time = DateTime.Now,
                                ioo_update_by = "Admin",
                                ioo_update_time = DateTime.Now,
                            };
                            myDbContext.inv_other_outbound.Add(inv_other_outbound);
                        }
                    }
                }

                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，该盘点订单已生成入库/出库单");
            }
            catch (DbUpdateException ex)
            {
                // 如果没有找到库存记录，则返回特定的消息
                if (ex.Message.Contains("没有找到对应的库存记录"))
                {
                    return Ok("审核成功，但未找到库存记录进行更新");
                }
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }
    }
}
